package com.example.demo.config;


import com.example.demo.dao.*;
import com.example.demo.po.*;
import com.example.demo.service.TBizAuctionRecordService;
import com.example.demo.service.TBizAuctionRemindService;
import com.example.demo.util.AcutionCache;
import com.example.demo.util.DateUtil;
import com.example.demo.util.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;


@Component
public class TimeTaskController {

    private static Map<String,String> userMap =new HashMap<>();

    @Autowired
    TBizAuctionArtDAO tBizAuctionArtDAO;
    @Autowired
    TBizAuctionRecordDAO tBizAuctionRecordDAO;
    @Autowired
    WxUserInfoDAO wxUserInfoDAO;
    @Autowired
    TBizAuctionDAO tBizAuctionDAO;
    @Autowired
    TBizAuctionRecordService arService;
    @Autowired
    TBizOrderDAO tBizOrderDAO;
    @Autowired
    TBizAuctionRemindService tBizAuctionRemindService;
    @Autowired
    TBizShoppingDAO tBizShoppingDAO;
    @Autowired
    TBizArtDAO tBizArtDAO;

    /**
     * 每分钟执行查看拍卖行状态
     */
//    @Scheduled(cron="0 0/1 * * * ?" )
    public void auctionTask(){
        try{
            System.out.println("**************获取当前正在拍卖的拍卖行信息******");
            //获取当前正在拍卖的拍卖行信息
            List<TBizAuctionArt> list = tBizAuctionArtDAO.findByTime(DateUtil.formatDate(new Date()));
            if(list!=null && list.size()>0){
                AcutionCache ac = new AcutionCache();
                for(TBizAuctionArt aa:list){
                    Integer id = aa.getId();
                    String aucId = aa.getAuctionid();
                    String artcode = aa.getArtcode();
                    String statingprice = aa.getStatingprice();
                    String increaseprice = aa.getIncreaseprice();
                    String bottomprice = aa.getBottomprice();
                    String endTime = aa.getEndTime();
                    List<TBizAuctionRecord> mlist = ac.getCodeMap(aucId+"_"+artcode);
                    String nowTime = DateUtil.formatDate(new Date());
                    System.out.println("nowTime is " + nowTime);
                    if(mlist!=null && mlist.size()>0){
                        int index = mlist.size()-1;
                        TBizAuctionRecord map = mlist.get(index);
                        String newPrice = map.getNewPrice();
                        String newTime = map.getCreatTime();
                        boolean times = (DateUtil.dateMinInteval(nowTime,newTime)-5)>0?true:false;
                        boolean prices = Double.valueOf(bottomprice)>Double.valueOf(newPrice);
                        //最新一次出价5分钟后没有人出价且低于保底价 自动加价一次
                        if(times && prices){
                            System.out.println("*****自动出价*****");
                            TBizAuctionRecord map1 = new TBizAuctionRecord();
                            Double newPrices = Double.valueOf(newPrice)+Double.valueOf(increaseprice);
                            System.out.println("*******自 newPrice*********"+newPrice);
                            map1.setNewPrice(newPrices.toString());
                            map1.setArtCode(artcode);
                            map1.setAuctionId(aucId);
                            map1.setCreatTime(DateUtil.formatDate(new Date()));
                            map1.setUserId(getUserMap());
                            ac.setCodeMap(aucId+"_"+artcode,map1);
                        }
                        boolean lastTime = DateUtil.dateMinInteval(endTime,newTime)-5>0?true:false;
                        //如果最后一次叫价时间距离结束时间不到5分钟 则延长5分钟时间
                        if(!lastTime){
                            String newEndTime = DateUtil.addMinNumsDate(nowTime,5);
                            TBizAuctionArt taa = new TBizAuctionArt();
                            taa.setId(id);
                            taa.setEndTime(newEndTime);
                            taa.setAddTime("5");
                            tBizAuctionArtDAO.update(taa);
                        }
                    }else {
                        //拍卖开始没有人叫价 自动叫一次价
                        TBizAuctionRecord ar = new TBizAuctionRecord();
                        Double newPrice = Double.valueOf(statingprice)+Double.valueOf(increaseprice);
                        ar.setNewPrice(newPrice.toString());
                        ar.setArtCode(artcode);
                        ar.setAuctionId(aucId);
                        ar.setCreatTime(DateUtil.formatDate(new Date()));
                        ar.setUserId(getUserMap());
                        ac.setCodeMap(aucId+"_"+artcode,ar);
                    }
                }
            }
            System.out.println("**************获取当前正在拍卖的拍卖行信息  end******");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
//
    /**
     * 拍卖结束
     */
//    @Scheduled(cron="0 0/5 * * * ?" )
    public void auctionEndTask(){
        try{
            System.out.println("***************************定时任务的查询拍卖记录结束的**********************");
            //获取今天已经结束拍卖的拍卖信息
            List<TBizAuctionArt> list = tBizAuctionArtDAO.findByEndTime(DateUtil.formatDate(new Date()));
            if(list!=null && list.size()>0){
                AcutionCache ac = new AcutionCache();
                List<TBizAuctionRecord> allList = new ArrayList<>();
                List<String> keyList = new ArrayList<>();
                for(TBizAuctionArt aa:list){
                    List<TBizAuctionRecord> arList = ac.getCodeMap(aa.getAuctionid()+"_"+aa.getArtcode());
                    if(arList!=null && arList.size()>0){
                        arService.saveAll(arList);
                        allList.addAll(arList);
                        keyList.add(aa.getAuctionid()+"_"+aa.getArtcode());
                        System.out.println(aa.getAuctionid()+"的拍卖记录");
                    }
                }
                if(allList!=null && allList.size()>0){
                   int i = tBizAuctionRecordDAO.insertList(allList);
                   if(i>0){
                       for (String key :keyList){
                           ac.remove(key,key);
                       }
                   }
                }

            }
            System.out.println("***************************查询拍卖记录结束的*** end*******************");
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 定时退保证金
     */
//    @Scheduled(cron="0 0 22 * * ?" )
    public  void orderEdit(){
        try{
            System.out.println("*************保证金退还 开始*************************");
            Date yesterDay = DateUtil.yesterdayTime();
            Date currentDay = DateUtil.currentTime(-3);
            String yDay = DateUtil.formatDate(yesterDay,"yyyy-MM-dd");
            String eDay = DateUtil.formatDate(currentDay,"yyyy-MM-dd");
//            String days = DateUtil.currentDateString();
//            System.out.println(days);
//            System.out.println(eDay);
            //查询前3天的拍卖会信息
            TBizAuction auction = new TBizAuction();
            auction.setStatetime(eDay);
            auction.setEndtime(yDay);
//            auction.setEndtime(days);
            List<TBizAuction> aList = tBizAuctionDAO.findBytime(auction);
            if(aList!=null && aList.size()>0){
                for(TBizAuction a :aList){
                    System.out.println("拍卖会ID is "+a.getAuctionid());
                    //获取该拍卖会没有拍中保证金订单
                    List<TBizOrder> oList = tBizOrderDAO.backBZJ(a.getAuctionid());
                    //获取该拍卖会拍中且支付完成的保证金订单
                    List<TBizOrder> oList1 = tBizOrderDAO.payBackBZJ(a.getAuctionid());
                    if(oList!=null && oList.size()>0){
                        for(TBizOrder o:oList){
                            String orderid = o.getOrderid();
                            String ticketid = o.getTicketid();
                            Double price = Double.valueOf(o.getPrice())*100;
                            DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                            String p =decimalFormat.format(price);
                            System.out.println("未拍中订单号 is "+a.getAuctionid());
                            System.out.println("保证金价格 is "+p +"分");
                            //调用微信退还接口
                            boolean resulrs =WxUtil.returnMoney(ticketid,orderid,p);
//                            boolean resulrs = true;
                            if(resulrs){
                                //修改订单状态
                                o.setOrderstate("4");
                                o.setJzstate("4");
                                tBizOrderDAO.update(o);
                                //发生退款信息
                                Map<String, String> map = new HashMap<>();
                                map.put("key1",o.getOrderid());
                                map.put("key2",a.getAuctionname());
                                map.put("key3",o.getPrice());
                                map.put("key4","");
                                WxUtil.sendType(o.getUserid(),"3",map);
                            }
                        }
                    }
                    if(oList1!=null && oList1.size()>0){
                        for(TBizOrder o:oList1){
                            System.out.println("拍卖会ID is "+a.getAuctionid());
                            String orderid = o.getOrderid();
                            String ticketid = o.getTicketid();
                            Double price = Double.valueOf(o.getPrice())*100;
                            DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                            String p =decimalFormat.format(price);
                            System.out.println(decimalFormat.format(price));
                            System.out.println("拍中订单号 is "+a.getAuctionid());
                            System.out.println("保证金价格 is "+p +"分");
                            //调用微信退还接口
                            boolean resulrs =WxUtil.returnMoney(ticketid,orderid,p);
//                            boolean resulrs = true;
                            if(resulrs){
                                //修改订单状态
                                o.setOrderstate("4");
                                o.setJzstate("4");
                                tBizOrderDAO.update(o);
                                //发生退款信息
                                Map<String, String> map = new HashMap<>();
                                map.put("key1",o.getOrderid());
                                map.put("key2",a.getAuctionname());
                                map.put("key3",o.getPrice());
                                map.put("key4","");
                                WxUtil.sendType(o.getUserid(),"3",map);
                            }
                        }
                    }
                }
            }
            System.out.println("*************保证金退还 end*************************");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 开拍签提醒
     */
//    @Scheduled(cron="0 0/1 * * * ?" )
    public void aucStateRemind(){
        System.out.println("*************开拍签提醒*************************");
        List<TBizAuctionRemind> list = tBizAuctionRemindService.getAlllist();
        if(list!=null && list.size()>0){
            List<Integer> idList = new ArrayList<>();
            for(TBizAuctionRemind ar :list){
                Map<String, String> map = new HashMap<>();
                map.put("key1",ar.getAucName());
                map.put("key2",ar.getStateTime());
                map.put("key3","距离你预约的活动开始仅剩10分钟");
                if(WxUtil.sendType(ar.getUserId(),"5",map)){
                    idList.add(ar.getId());
                }
            }
            tBizAuctionRemindService.delAll(idList);
        }
        System.out.println("*************保证金退还 end*************************");
    }


    /**
     * 订单和购物车超过时间没有处理的清除
     */
//   @Scheduled(cron="0 0/30 * * * ?" )
   public void removeALL(){
        System.out.println("*************开始处理*************************");
        //获取超过2小时没有支付的订单信息
        List<TBizOrder> list = tBizOrderDAO.findListByTime();
        if(list!=null && list.size()>0){
            for(TBizOrder s :list){
                //商城订单取消
                if("1".equals(s.getType().trim())){
                    s.setOrderstate("3");
                    tBizOrderDAO.update(s);
                    //作品改为上架
                    TBizArt art = new TBizArt();
                    art.setuType("order");
                    art.setOrderId(s.getOrderid());
                    art.setSalestate("0");
                    tBizArtDAO.editStateByshopId(art);
                }
            }
        }
        //获取购物车6小时没有处理的
        List<TBizShopping> shopList = tBizShoppingDAO.findListByTime();
       if(shopList!=null && shopList.size()>0){
           List<String> idList = new ArrayList<>();
           for(TBizShopping s :shopList){
                idList.add(s.getId().toString());
                TBizArt art = new TBizArt();
                art.setArtcode(s.getArtId().trim());
                art.setSalestate("0");
                tBizArtDAO.updateByartCode(art);
            }
           tBizShoppingDAO.del(idList);
       }

        System.out.println("*************处理结束*************************");
    }







    public String getUserMap() {
        Map<String, String> map = userMap;
        if(map!=null&&map.size()>0){
        }else {
            List<WxUserInfo> list = wxUserInfoDAO.findByType(0);
            if(list!=null&&list.size()>0){
                for(WxUserInfo info :list){
                    userMap.put(info.getOpenid(),info.getNickName());
                }
            }
        }
        String[] keys = map.keySet().toArray(new String[0]);
        Random random = new Random();
        String randomKey = keys[random.nextInt(keys.length)];
        System.out.println("******sss*****"+randomKey);
        return randomKey;
    }
}
